//
//  YCVideoViewController.m
//  LOLBox
//
//  Created by mac on 15-3-26.
//  Copyright (c) 2015年 Honey. All rights reserved.
//

#import "YCVideoViewController.h"
#import "AFNetworking.h"
#import "PublicNavView.h"
#import "YCVideoModel.h"
#import "YCCollectionCell.h"
#import "YCNewCollectionCell.h"
#import "YCVideoList.h"
#import "YCVideoDownLoadViewController.h"

#define kVideotypeUrl @"http://lolbox.oss.aliyuncs.com/json/v4/videotype_3.json"

@interface YCVideoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    //用来判断是否是“最新”
    BOOL _isNew;
    
    //得到当前所在页面的网址
    NSString *_currentUrl;
}
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation YCVideoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _isNew = NO;
        self.view.backgroundColor = [UIColor clearColor];
        self.dataSource = [NSMutableArray array];
        
        [self createNavTitleView:@"视频"];
        [self createSearchBarBtn];
        [self createDownloadBarBtnWithTarget:self WithAction:@selector(pushDownload)];
    }
    return self;
}

- (void)pushDownload
{
    YCVideoDownLoadViewController *vdl = [[YCVideoDownLoadViewController alloc] init];
    [self.navigationController pushViewController:vdl animated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self AFN:kVideotypeUrl];
    [self createNavView];
    [self createCollectionView];
    
}

//数据请求
- (void)AFN:(NSString *)strUrl
{
    //遮挡
    //loadView
    CGRect loadFrame = self.view.bounds;
//    loadFrame.origin.y = 0;
    loadFrame.size.height = loadFrame.size.height;
    
    YCLoadingVIew *v = [[YCLoadingVIew alloc] initWithFrame:loadFrame withTitle:@"加载中"];
    [self.view addSubview:v];
    
    _currentUrl = strUrl;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:[NSString stringWithFormat:@"%@",strUrl] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            //NSLog(@"%@",arr);
        [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            
            YCVideoModel *m = [[YCVideoModel alloc] init];
            //判断
            if (_isNew)
            {
                m.Id = obj[@"id"];
                m.img = obj[@"img"];
                m.name = obj[@"name"];
                m.time = obj[@"time"];
                m.length = obj[@"length"];
                m.videoAddr = obj[@"video_addr"];
                m.videoAddrHigh = obj[@"video_addr_high"];
                m.videoAddrSuper = obj[@"video_addr_super"];
                m.youkuId = obj[@"youku_id"];
            }
            else
            {
                m.count = obj[@"count"];
                m.Id = obj[@"id"];
                m.img = obj[@"img"];
                m.name = obj[@"name"];
                m.time = obj[@"time"];
            }
            [_dataSource addObject:m];
        }];
        [self.collectionView reloadData];
        
        
        [v removeFromSuperview];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"fail");
    }];
}

- (void)createNavView
{
    NSArray *nameArr = @[@"系列",@"赛事",@"解说",@"最新"];
    NSArray *urlArr = @[@"http://lolbox.oss.aliyuncs.com/json/v4/videotype_3.json",
                        @"http://lolbox.oss.aliyuncs.com/json/v4/videotype_4.json",
                        @"http://lolbox.oss.aliyuncs.com/json/v4/videotype_2.json",
                        @"http://lolbox.oss.aliyuncs.com/json/videolist_99.json",];
    PublicNavView *navView = [[PublicNavView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    //navView.backgroundColor = [UIColor blueColor];
    // 第一步，把数组传过去
    [navView senderValue:nameArr andSecond:urlArr];
    //第二步，创建按钮
    [navView creatTheBtnAndIndex:0];
    //第三步，通过BLOCK回调得到网址
    [navView changValue:@"1" senderBlock:^(NSString *str,NSInteger index) {
        //NSLog(@"str :%@",str);
        
        if ([str isEqualToString:[urlArr lastObject]])
        {
            _isNew = YES;
        }
        else
        {
            _isNew = NO;
        }
        
        // 数据请求请清空数据
        [self.dataSource removeAllObjects];

        //执行下载 刷新数据
        [self AFN:str];
        
    }];
    
    [self.view addSubview:navView];
}

- (void)createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake(70, 90);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 30, CGRectGetWidth([[UIScreen mainScreen] bounds]), CGRectGetHeight([[UIScreen mainScreen] bounds]) - 30 - 50 - 64) collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"YCCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"YCNewCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"newcell"];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isNew)
    {
        YCNewCollectionCell *newcell = [collectionView dequeueReusableCellWithReuseIdentifier:@"newcell" forIndexPath:indexPath];
        if (self.dataSource.count > 0)
        {
            YCVideoModel *model = self.dataSource[indexPath.row];
            [newcell fillCellWithModel:model];
        }

        return newcell;
    }
    else
    {
        YCCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        
        if (self.dataSource.count > 0)
        {
            YCVideoModel *model = self.dataSource[indexPath.row];
            [cell fillCellWithModel:model];
        }
        
        return cell;
    }
    
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isNew)
    {
        
    }
    else
    {
        NSLog(@"点击第 %d",indexPath.row);
        YCVideoModel *m = self.dataSource[indexPath.row];
        
        //跳转到视频列表 传值过去
        YCVideoList *list = [[YCVideoList alloc] init];
        
        
        [list senderVaule:[self clipString:_currentUrl andId:[NSString stringWithFormat:@"%@",m.Id]]];
        [self.navigationController pushViewController:list animated:YES];
        //NSLog(@"1");
    }
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isNew)
    {
        return CGSizeMake(CGRectGetWidth(self.view.frame), 80);
    }
    else
    {
        return CGSizeMake(70, 90);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (_isNew)
    {
        return  UIEdgeInsetsMake(0, 0, 0, 0);
    }
    else
    {
        CGFloat lengFloat = CGRectGetWidth([[UIScreen mainScreen] bounds]);
        CGFloat spLeng = (lengFloat - 70 * 3) / 5;
        return  UIEdgeInsetsMake(5, spLeng, 5, spLeng);
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if (_isNew)
    {
        return 0;
    }
    else
    {
        return 5;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//字符串裁剪  /v4/videotype_4   ".json"
- (NSString *)clipString:(NSString *)str andId:(NSString *)Id;
{
    NSInteger length = [str length];
    //得到数字
    NSString *num = [str substringWithRange:NSMakeRange(length - 6, 1)];
    //NSLog(@"数字%@",num);
    
    NSString *s = [str substringToIndex:length - 16];
    //NSLog(@"字符组:%@",s);
    
    //拼接字符串
    NSString *lastStr = [NSString stringWithFormat:@"%@video/videolist_%@_%@_",s,num,Id];
    
    return lastStr;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
